<!-- 商户每日数据 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" :showExport="true" @changeSize="changeSize"
    @download="getExport" @changePage="changePage" @search="getSearchList" @sort="sortTable"
    @reset="onHideDetails(true)" @changeTh="data.dialogVisible = true">
    <template #form>
      <Operator ref="OperatorRef" @query="queryItem" />
      <el-form-item label="日期时间：">
        <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable :disabled-date="indexStore.disabledDateTime"/>
      </el-form-item>
    </template>
    <template #button>
      <div class="statistic flex">
        <el-button v-if="!indexStore.is_general_agent" type="warning" @click="data.query.is_usdt_show = data.query.is_usdt_show?0:1,getSearchList()">{{ data.query.is_usdt_show?'取消换算':'换算USDT' }}</el-button>
      </div>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
          :sortable="item.sortable ? 'custom' : false" show-overflow-tooltip>
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content>
                {{item.tips}}
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'game_bet'" #default="scope">
            <span class="colorText">{{ BigWan(scope.row.game_bet) }}</span>
          </template>
          <template v-if="item.prop == 'game_income'" #default="scope">
            <span :class="colorClass(scope.row.game_income)">{{
              BigWan(scope.row.game_income)
            }}</span>
          </template>
          <template v-if="item.prop == 'pump'" #default="scope">
            <span class="colorText">{{ BigWan(scope.row.pump) }}</span>
          </template>
          <template v-if="item.prop == 'history_game_income'" #default="scope">
            <span :class="colorClass(scope.row.history_game_income)">{{
              BigWan(scope.row.history_game_income)
            }}</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="90" align="center">
        <template #header>
          <el-tooltip effect="dark" content="查看当天商户的游戏详情数据" placement="top">
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          详情
        </template>
        <template #default="scope">
          <el-button type="primary" v-permiss="'/system/destroyManager'" size="small" @click="checkDetails(scope.row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData"></tableHeader>

  <!-- 游戏详情 -->
  <el-dialog v-model="data.isShowDetails" width="75%" title="游戏详情" :close-on-click-modal="false"
    :close-on-press-escape="false" @close="onHideDetails" top="8vh">
    <template #header>
      <p class="box-title mustPass">
        【{{ data.checkedItem.agent_id?data.checkedItem.agent_id:data.checkedItem.operated_id }}】 {{ data.checkedItem.account_name }}
      </p>
    </template>
    <div v-loading="indexStore.moduleLoading" class="dialogMaxMultipleButton">
      <SearchTable :query="data.queryDetails" :list="data.listDetails" :total="data.totalDetails" :showSet="false"
      @changeSize="changeSizeDetails" @changePage="changePageDetails" @search="getSearchDetailsList" @reset="onHideDetails(true)" @sort="sortTableDetails">
        <template #form>
          <el-form-item label="日期时间：">
            <el-date-picker v-model="data.queryDetails.date" type="daterange" range-separator="-" :disabled-date="indexStore.disabledDateTime"
              start-placeholder="请选择开始时间" end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable />
          </el-form-item>
          <el-form-item label="游戏：">
            <el-select v-model="data.queryDetails.game_id" placeholder="请选择" filterable>
              <el-option label="全部" :value="-1" />
              <el-option v-for="item in indexStore.gameArray" :key="item.value"
                :label="'【' + item.value + '】' + item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </template>
        <template #table>
          <template v-for="(item, index) in data.fieldDetails" :key="index">
            <el-table-column v-if="item.visible" :prop="item.prop" :label="item.label" :width="item.width"
              :sortable="item.sortable ? true : false" show-overflow-tooltip>
              <template #header>
                <el-tooltip v-if="item.tips" effect="dark" placement="top">
                  <template #content>
                    {{item.tips}}
                  </template>
                  <el-icon class="ques-tips">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                {{ item.label }}
              </template>
              <template v-if="item.prop == 'game_id'" #default="scope">
                <GameHeaderInfo :game_id="scope.row.game_id" />
              </template>
              <template v-if="item.prop == 'game_bet'" #default="scope">
              <span class="colorText">{{ scope.row.game_bet }}</span>
            </template>
              <template v-if="item.prop == 'game_income'" #default="scope">
                <span :class="colorClass(scope.row.game_income)">{{
                   BigWan(scope.row.game_income)
                }}</span>
              </template>
              <template v-if="item.prop == 'history_game_income'" #default="scope">
                <span :class="colorClass(scope.row.history_game_income)">{{
                   BigWan(scope.row.history_game_income)
                }}</span>
              </template>
              <template v-if="item.prop == 'radio'" #default="scope">
                {{ RtpPercent(scope.row.game_win_person, scope.row.valid_user) }}
              </template>
            </el-table-column>
          </template>
        </template>
      </SearchTable>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { selectToLabel, colorClass, AgentCurrency } from '@/utils/index'
import { exportToExcel } from '@/utils/export'
import { BigWan, RtpPercent } from '@/utils/math'
import { getDateDay, setTimeValue, setTimestampTimeDate } from '@/utils/time'
import { getMerchantDaily, getMerchantDailyDetails, getMerchantDailySum } from '@/api/gameReport'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    is_usdt_show: 0,
    date: [getDateDay(0), getDateDay(0)],
    order_type: '',
    up_or_down: '',
  },
  list: [],
  total: 0,
  fields: [
    { label: '日期', prop: 'date', width: '135', visible: true, tips: '筛选日期展示，报表以筛选日期每日落一条数据' },
    { label: '商户昵称', prop: 'account_name', width: '120', visible: true, tips: '商户的名称说明' },
    { label: '币种', prop: 'currency', width: '100', visible: true, tips: '商户游戏结算所使用的货币，不轻易更改，创建商户时的信息设定' },
    { label: '当天输赢', prop: 'game_income', width: '160', visible: true, sortable: true, tips: '商户当天日期的输赢情况正为盈利、负为亏损' },
    { label: '历史输赢', prop: 'history_game_income', width: '170', visible: true, sortable: true, tips: '商户历史总输赢情况正为盈利、负为亏损跟筛选日期无关' },
    { label: 'RTP', prop: 'rtp', width: '110', visible: true, sortable: true, tips: '商户的当天游戏回报率值越高玩家盈利越多，值越低平台盈利越多' },
    { label: '注单金额', prop: 'game_bet', width: '140', visible: true, sortable: true, tips: '商户旗下玩家当天的下注金额数量' },
    { label: '抽水额度', prop: 'pump', width: '140', visible: true, sortable: true, tips: '统计筛选日期内的游戏抽水（含利润率）费用' },
    { label: '注单数', prop: 'game_count', width: '130', visible: true, sortable: true, tips: '商户旗下玩家当天的下注次数' },
    { label: '投注用户数', prop: 'valid_user', width: '155', visible: true, sortable: true, tips: '商户当天有过下注行为的玩家数量去重' },
    { label: '注册用户数', prop: 'new_user', width: '155', visible: true, sortable: true, tips: '商户当天的新增注册玩家数量' },
    { label: '登录用户数', prop: 'in_game_num', width: '155', visible: true, sortable: true, tips: '商户旗下玩家当天登录进游戏的人数去重' },
  ],
  dialogVisible: false,
  isShowDetails: false,
  checkedItem: {} as any,
  exportLoading: false,
  totalForm:{
    game_bet: 0,
    game_count: 0,
    game_income: 0,
    history_game_income: 0,
    in_game_num: 0,
    new_user: 0,
    valid_user: 0,
  } as any,
  queryDetails: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    game_id: -1,
    date: [getDateDay(0), getDateDay(0)],
    order_type: '',
    up_or_down: '',
  },
  listDetails: [],
  totalDetails: 0,
  fieldDetails: [
    { label: '日期', prop: 'date', width: '120', visible: true, tips: '筛选日期展示，报表以筛选日期每日落一条数据' },
    { label: '游戏名称', prop: 'game_id', width: '180', visible: true, tips: '游戏名称的描述说明' },
    { label: '币种', prop: 'currency', width: '100', visible: true, tips: '商户游戏结算所使用的货币，不轻易更改，创建商户时的信息设定' },
    { label: '当天输赢', prop: 'game_income', width: '', visible: true, sortable: true, tips: '游戏的当天输赢情况正为盈利、负为亏损' },
    { label: '人数赢百分比', prop: 'radio', width: '145', visible: true, tips: '游戏当天的玩家盈利的人数占比，值越高，在游戏赢的玩家数越多' },
    { label: 'RTP', prop: 'rtp', width: '95', visible: true, tips: '游戏当天回报率值越高玩家盈利越多，值越低平台盈利越多' },
    { label: '历史输赢', prop: 'history_game_income', width: '', visible: true, sortable: true, tips: '游戏的历史输赢情况正为盈利、负为亏损跟筛选日期无关' },
    { label: '注单金额', prop: 'game_bet', width: '', visible: true, sortable: true, tips: '游戏当天的玩家下注金额数量' },
    { label: '注单数', prop: 'game_count', width: '125', visible: true, sortable: true, tips: '游戏当天的玩家下注次数' },
    { label: '投注用户', prop: 'valid_user', width: '140', visible: true, sortable: true, tips: '游戏当天有过下注行为的玩家数量去重' }
  ]
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}

onMounted(async () => {
  getSearchList()
  // getSearchSumList()
})

const getSearchList = async () => {
  indexStore.setPageLoading(true)
  data.query = setTimeValue(data.query)
  let res = await getMerchantDaily(data.query)
  res.data.list?.forEach((item: any) => {
    item.date = setTimestampTimeDate(item.date)
    item.rtp = RtpPercent(item.game_win, item.game_bet)
    item.currency = AgentCurrency(item.agent_id)
  })
  data.list = res.data.list
  data.total = res.data.total
}

const getSearchSumList = async () => {
  data.query = setTimeValue(data.query)
  let res = await getMerchantDailySum(data.query)
  data.totalForm = res.data
}

// 详情
const checkDetails = async (row: {
  agent_id: number
  operated_id: number
  agent_name: string
  date: string
}) => {
  Object.assign(data.checkedItem, row)
  data.queryDetails.agent_id = row.agent_id
  data.queryDetails.operated_id = row.operated_id
  data.queryDetails.date = [row.date, row.date]
  getSearchDetailsList()
}
const getSearchDetailsList = async () => {
  indexStore.setModuleLoading(true)
  data.listDetails = []
  let query = setTimeValue(data.queryDetails);
  let res = await getMerchantDailyDetails(query)
  data.isShowDetails = true
  res.data?.list?.forEach((item: any) => {
    item.date = setTimestampTimeDate(item.date)
    item.rtp = RtpPercent(item.game_win, item.game_bet)
    item.game_bet = BigWan(item.game_bet)
    item.currency = item.agent_id?AgentCurrency(item.agent_id):'-'
  })
  data.listDetails = res.data.list
  data.totalDetails = res.data.total
}

// 排序
const sortTable = (val: any) => {
  data.query.up_or_down = val.order
  if (val.prop == 'rtp') {
    data.query.order_type = 'game_win/game_bet'
  } else {
    data.query.order_type = val.prop
  }
  getSearchList()
}
const sortTableDetails = (val: any) => {
  data.queryDetails.up_or_down = val.order
  if (val.prop == 'rtp') {
    data.queryDetails.order_type = 'game_win/game_bet'
  } else {
    data.queryDetails.order_type = val.prop
  }
  getSearchDetailsList()
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}
const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}
const changeSizeDetails = (val: number) => {
  data.queryDetails.size = val
}
const changePageDetails = (val: number) => {
  data.queryDetails.page = val
  getSearchDetailsList()
}

// 导出
const getExport = async () => {
  let query = JSON.parse(JSON.stringify(data.query));
  query.page = 1
  query.size = 10000
  let res = await getMerchantDaily(query);
  let dataList = res.data.list;

  let header: string[] = []
  let list: never[][] = []

  data.fields.forEach((item) => {
    header.push(item.label)
  })

  dataList.forEach((item: { [x: string]: any }, index: any) => {
    let arr: never[] = []
    data.fields.forEach((x) => {
      switch (x.prop) {
        case 'date':
          arr.push(setTimestampTimeDate(item[x.prop]) as never)
          break
        case 'agent_id':
          arr.push(selectToLabel(indexStore.agentArray, item[x.prop]) as never)
          break
        case 'currency':
          arr.push(selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentArray, item['agent_id'],'currency','value')) + '(' + selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentArray, item['agent_id'],'currency','value'), 'type', 'value') + ')' + '-' + selectToLabel(indexStore.currentArray, selectToLabel(indexStore.agentArray, item['agent_id'],'currency','value'), 'remark', 'value') as never)
          break
        case 'game_income':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'history_game_income':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'game_bet':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'game_win':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'rtp':
          arr.push(RtpPercent(BigWan(item['game_win']), BigWan(item['game_bet'])) as never)
          break
        default:
          arr.push(item[x.prop] as never)
          break
      }
    })
    list.push(arr)
  })
  exportToExcel(list, header, '商户每日数据')
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const OperatorRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.dialogVisible = false
  data.exportLoading = false
  if (show) {
    if (data.isShowDetails) {
      data.queryDetails = {
        page: 1,
        size: 50,
        agent_id: data.queryDetails.agent_id,
        operated_id: data.queryDetails.operated_id,
        game_id: -1,
        date: [data.checkedItem.date, data.checkedItem.date],
        order_type: '',
        up_or_down: '',
      },
        getSearchDetailsList()
    } else {
      data.query = {
        page: 1,
        size: 50,
        agent_id: -1,
        operated_id: -1,
        is_usdt_show: 0,
        date: [getDateDay(0), getDateDay(0)],
        order_type: '',
        up_or_down: '',
      }
      getSearchList()
    }
    OperatorRef.value.onHideDetails()
  }
}
</script>
<style scoped lang="scss"></style>